var scene, camera, renderer, pointsGeometry;
var swiper;
var modelList = [];
var activeIndex = 0;
var ASSETSURL = "../assets/03/"; // 资源主目录路径
var partNum = 100,
  PointNum = 15000,
  size = 10;

var textureLoader = new THREE.TextureLoader();
textureLoader.crossOrigin = "";
//  var mapDot = textureLoader.load(ASSETSURL + "imgs/star.png");
var mapDot = createMap();

(function () {
  addSwiper();
  initVariable(); // 初始化基础环境
  initAroundParticles(); // 初始化环境粒子
  initMainParticles(); // 初始变换粒子
  initModel(); // 初始化模型
  firstAnimation(addFullEvent); // 首次动画
  loop(); // 主循环
  addLight();
})();
function addSwiper() {
  swiper = new Swiper(".swiper-container", {
    direction: "vertical",
    initialSlide: activeIndex,
    pagination: {
      el: ".swiper-pagination",
      clickable: true,
      renderBullet: function (index, className) {
        var names = [
          "WarGreymon",
          "MetalGarurumon",
          "Kabuterimon",
          "Angewomon",   
          "Zudomon",
          "Togemon",
          "MagnaAngemon",
          "Birdramon",
        ];
        return (
          '<p class="name-bullet ' + className + '">' + names[index] + "</p>"
        );
      },
    },
    resistanceRatio: 0,
    mousewheel: true,
    disableScroll: false,
    on: {
      slideChange: function () {
        changeModel(this.activeIndex);
      },
    },
  });
  swiper.disable();
}
function addFullEvent() {
  console.log(swiper);
  swiper.enable();
}

function addLight() {
  // // new THREE.OrbitControls(camera, renderer.domElement);
  var ambientLight = new THREE.AmbientLight(0xffffff);
  ambientLight.intensity = 10;
  scene.add(ambientLight);
}

function loop() {
  requestAnimationFrame(loop);
  renderer.render(scene, camera);
  camera.lookAt(scene.position);
  TWEEN.update();
}

function initModel() {
  var loader = new THREE.OBJLoader();
  loader.load(ASSETSURL + "model/WarGreymon/WarGreymon.obj", function (mesh) {
    console.log(mesh);
    var _arr = [];
    mesh.children[0].geometry.attributes.position.array.forEach(function (
      item,
      index
    ) {
      var n = item * 210;
      if (index % 3 == 1) {
        n -= 250;
      }
      _arr.push(n);
    });
    modelList[0] = _arr;
  });

  loader.load(
    ASSETSURL + "model/MetalGarurumon/MetalGarurumon.obj",
    function (mesh) {
      console.log(mesh);
      var _arr = [];
      mesh.children[0].geometry.attributes.position.array.forEach(function (
        item,
        index
      ) {
        var n = item * 125;
        if (index % 3 == 1) {
          n -= 150;
        }
        _arr.push(n);
      });
      modelList[1] = _arr;
    }
  );

  loader.load(ASSETSURL + "model/Kabuterimon/Kabuterimon.obj", function (mesh) {
    console.log(mesh);
    var _arr = [];
    mesh.children[0].geometry.attributes.position.array.forEach(function (
      item,
      index
    ) {
      var n = item * 210;
      if (index % 3 == 1) {
        n -= 220;
      }
      _arr.push(n);
    });
    modelList[2] = _arr;
  });

  loader.load(ASSETSURL + "model/Angewomon/Angewomon.obj", function (mesh) {
    console.log(mesh);
    var _arr = [];
    var _list = [];
    mesh.children.forEach(function (child) {
      child.geometry.attributes.position.array.forEach(function (item) {
        _list.push(item);
      });
    });

    _list.forEach(function (item, index) {
      var n = item * 320;
      if (index % 3 == 1) {
        n -= 150;
      }
      _arr.push(n);
    });
    modelList[3] = _arr;
  });

  loader.load(ASSETSURL + "model/Birdramon/Birdramon.obj", function (mesh) {
    console.log(mesh);
    var _arr = [];
    var _list = [];
    mesh.children.forEach(function (child) {
      child.geometry.attributes.position.array.forEach(function (item) {
        _list.push(item);
      });
    });

    _list.forEach(function (item, index) {
      var n = item * 160;
      if (index % 3 == 1) {
        n -= 150;
      }
      _arr.push(n);
    });
    modelList[7] = _arr;
  });

  loader.load(ASSETSURL + "model/Zudomon/Zudomon.obj", function (mesh) {
    console.log(mesh);
    var _arr = [];
    var _list = [];
    mesh.children.forEach(function (child) {
      child.geometry.attributes.position.array.forEach(function (item) {
        _list.push(item);
      });
    });

    _list.forEach(function (item, index) {
      var n = item * 180;
      if (index % 3 == 1) {
        n -= 170;
      }
      _arr.push(n);
    });
    modelList[5] = _arr;
  });

  loader.load(ASSETSURL + "model/Togemon/Togemon.obj", function (mesh) {
    console.log(mesh);
    var _arr = [];
    var _list = [];
    mesh.children.forEach(function (child) {
      child.geometry.attributes.position.array.forEach(function (item) {
        _list.push(item);
      });
    });

    _list.forEach(function (item, index) {
      var n = item * 210;
      if (index % 3 == 1) {
        n -= 230;
      }
      _arr.push(n);
    });
    modelList[6] = _arr;
  });

  loader.load(
    ASSETSURL + "model/MagnaAngemon/MagnaAngemon.obj",
    function (mesh) {
      console.log(mesh);
      var _arr = [];
      var _list = [];
      mesh.children.forEach(function (child) {
        child.geometry.attributes.position.array.forEach(function (item) {
          _list.push(item);
        });
      });

      _list.forEach(function (item, index) {
        var n = item * 150;
        if (index % 3 == 1) {
          n -= 230;
        }
        _arr.push(n);
      });
      modelList[4] = _arr;
    }
  );

  // fetch(ASSETSURL + "model/2ac.json")
  //   .then(function (response) {
  //     return response.json();
  //   })
  //   .then(function (data) {
  //     var _arr = [];
  //     data.vertices.forEach(function (item, index) {
  //       _arr.push(item * 320);
  //     });
  //     modelList[0] = _arr;
  //   });
}

function createMap() {
  let canvas = document.createElement("canvas");
  canvas.width = 16;
  canvas.height = 16;

  let ctx = canvas.getContext("2d");

  ctx.save();
  let gradient = ctx.createRadialGradient(
    canvas.width / 2,
    canvas.height / 2,
    0,
    canvas.width / 2,
    canvas.height / 2,
    canvas.width / 2
  );
  gradient.addColorStop(0, "rgba(255,255,255,1)");
  gradient.addColorStop(0.2, "rgba(0,255,255,1)");
  gradient.addColorStop(0.4, "rgba(0,0,255,1)");
  gradient.addColorStop(1, "rgba(0,0,0,0)");
  ctx.fillStyle = gradient;
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.restore();

  let texture = new THREE.Texture(canvas);
  texture.needsUpdate = true;
  return texture;
}
var is_start = true;
function changeModel(index) {
  activeIndex = index || 0;
  var data = modelList[index];
  if (!data) return;
  swiper.disable();
  
  if (is_start) {
    changeToAnimation(data);
    is_start = false;
  }
  else {
    translateAnimation(function () {
      changeToAnimation(data);
    });
  }


}

function translateAnimation(callback) {
  var twInstance = new TWEEN.Tween(pointsGeometry.attributes.position.array);
  var _obj = {};
  pointsGeometry.attributes.position.array.forEach(function (item, index) {
    _obj[index] = item*20*Math.random();
  });
  twInstance
    .to(_obj, 600)
    .onComplete(function () {
      setTimeout(function () {
        callback && callback();
      })
    })
    .onUpdate(function (_data) {
      pointsGeometry.setAttribute(
        "position",
        new THREE.Float32BufferAttribute(_data, 3)
      );
    })
    .easing(TWEEN.Easing.Cubic.InOut)
    .start();
}

function changeToAnimation(data) {
  var twInstance = new TWEEN.Tween(pointsGeometry.attributes.position.array);
  var _obj = {};
  pointsGeometry.attributes.position.array.forEach(function (item, index) {
    _obj[index] = data[index] || 0;
  });
  twInstance
    .to(_obj, 1000)
    .onComplete(function () {
      swiper.enable();
    })
    .onUpdate(function (_data) {
      pointsGeometry.setAttribute(
        "position",
        new THREE.Float32BufferAttribute(_data, 3)
      );
    })
    .easing(TWEEN.Easing.Exponential.In)
    // .delay(300 * Math.random())
    .start();
}

function firstAnimation(callback) {
  var baseVal = -Math.PI * 0.6;
  group.rotation.y = baseVal;
  var twInstance = new TWEEN.Tween(group.rotation);
  twInstance
    .to(
      {
        y: 0, // Math.PI/180 * 45,
      },
      5000
    )
    .delay(100)
    .onComplete(function () {
      // 绑定鼠标动画
      document.addEventListener("mousemove", onDocumentMouseMove, false);
      // 自动切换到第一个模型
      changeModel(activeIndex);
      callback && callback();
    })
    .easing(TWEEN.Easing.Sinusoidal.InOut)
    .start();
}

function initMainParticles() {
  // 初始化geometry
  pointsGeometry = new THREE.BufferGeometry();

  var points = [];
  for (var i = 0; i < PointNum; i++) {
    var vertex = new THREE.Vector3();
    vertex.x = rangeRandom(-window.innerWidth, window.innerWidth);
    vertex.y = rangeRandom(-window.innerHeight, window.innerHeight);
    vertex.z = rangeRandom(-window.innerWidth, window.innerWidth);
    points.push(vertex);
  }
  pointsGeometry.setFromPoints(points);
  var material = new THREE.PointsMaterial({
    size: size,
    sizeAttenuation: true,
    transparent: true,
    depthWrite: false,
    map: mapDot,
    // vertexColors: THREE.VertexColors,
  });
  var particles = new THREE.Points(pointsGeometry, material);
  particles.position.set(0, 0, 0);
  group.add(particles);
}

function initAroundParticles() {
  var around = new THREE.BufferGeometry();
  var minZVal = window.innerWidth * 0.7;
  var minYVal = window.innerHeight * 0.8;
  // 初始化漫游粒子
  var points = [];
  // var colors=[];
  // var color = new THREE.Color();
  for (var i = 0; i < partNum; i++) {
    var vertex = new THREE.Vector3();
    vertex.x = rangeRandom(-minZVal, minZVal); // 水平方向
    vertex.y = rangeRandom(-minYVal, minYVal); // 垂直方向
    vertex.z = rangeRandom(-minZVal, minZVal);
    points.push(vertex);
    // color.setRGB(255, 255, 255);
    // colors.push(color.r, color.g,color.b);
  }
  around.setFromPoints(points);
  // around.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
  // around.setAttribute("position", new THREE.Float32BufferAttribute(points, 3));
  var material = new THREE.PointsMaterial({
    size: size * 1.5,
    sizeAttenuation: true,
    transparent: true,
    map: mapDot,
    depthWrite: false,
    // vertexColors: THREE.VertexColors,
  });
  var aroundPoints = new THREE.Points(around, material);
  aroundPoints.position.set(0, 0, 0);
  group.add(aroundPoints);

  new TWEEN.Tween(aroundPoints.rotation)
    .to(
      {
        y: Math.PI * 2,
      },
      20000
    )
    .repeat(Infinity)
    .start();
}

function initVariable() {
  // 创建摄像机
  camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    30,
    10000
  );
  camera.position.z = 680;
  // 初始化场景
  scene = new THREE.Scene();
  // 场景雾化
  scene.fog = new THREE.FogExp2(0x05050c, 0.0005);

  group = new THREE.Group();
  scene.add(group);

  // 初始化renderer
  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setClearColor(0x05050c);
  document.getElementById("container").appendChild(renderer.domElement);

  // 监听窗口尺寸改变
  window.addEventListener("resize", onWindowResize, false);
}

function onWindowResize() {
  // 窗口尺寸改变
  try {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
  } catch (error) {
    console.log(error);
  }
}

function rangeRandom(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

function onDocumentMouseMove(event) {
  event.preventDefault();
  var rotateY =
    ((event.pageX - window.innerWidth / 2) / (window.innerWidth * 5)) *
    2 *
    Math.PI;
  var rotateX =
    ((event.pageY - window.innerHeight / 2) / (window.innerHeight * 30)) *
    2 *
    Math.PI;
  new TWEEN.Tween(group.rotation)
    .to(
      {
        x: rotateX,
        y: rotateY,
      },
      200
    )
    // .easing(TWEEN.Easing.Cubic.In)
    .start();
}
